<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card class="box-card">
      <div>
        <!-- 搜索与添加 -->
        <el-row :gutter="20">
          <el-col :span='7'>
            <el-input @clear="getUsersList" clearable v-model="queryInfo.query" placeholder="输入搜索内容">
              <el-button @click="getUsersList" slot="append" icon="el-icon-search"></el-button>
            </el-input>
          </el-col>
          <el-col :span='4'>
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 用戶列表頁 -->
        <el-table boder :data="usersList" border stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <el-table-column label="姓名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="电话" prop="mobile"></el-table-column>
          <el-table-column label="身份" prop="role_name"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <!-- {{scope.row}}作用域插槽 -->
              <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="170px">
            <template slot-scope="scope">
              <!-- 修改按钮 -->
              <el-tooltip class="item" effect="dark" content="修改" :enterable="false" placement="top">
                <el-button @click="showEditDialog(scope.row.id)" type="primary" icon="el-icon-edit" size="mini" circle></el-button>
              </el-tooltip>
              <!-- 删除按钮 -->
              <el-tooltip class="item" effect="dark" content="删除" :enterable="false" placement="top">
                <el-button @click="removeUserById(scope.row.id)" type="danger" icon="el-icon-delete" size="mini" circle></el-button>
              </el-tooltip>
              <!-- 分配角色按钮 -->
              <el-tooltip class="item" effect="dark" content="分配角色" :enterable="false" placement="top">
                <el-button @click="setRole(scope.row)" type="success" icon="el-icon-setting" size="mini" circle></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryInfo.pagenum"
        :page-sizes="[2, 4, 6, 8]" :page-size="queryInfo.pagesize" layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!-- 添加用户对话区域 -->
    <el-dialog title="添加用户" @close="addDialogClosed" :visible.sync="addDialogVisible" width="50%">
      <!-- 对话框按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <!-- 表单区 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input type="email" v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input type="num" v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog @close="editDialogClosed" title="修改用户信息" :visible.sync="editDialogVisible" width="50%">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input disabled v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
      <div>
        <p>当前用户：{{userInfo.username}}</p>
        <p>当前角色：{{userInfo.role_name}}</p>
        <p>分配新角色：
          <el-select v-model="selectedRoleId" placeholder="请选择">
            <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱规则
    var checkEmail = (rules, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^([a-zA-z0-9_-])+@([a-zA-z0-9_-])+([a-zA-z0-9_-])+/
      if (regEmail.test(value)) {
        // 合法邮箱
        return callback()
      }
      // 不合法的邮箱
      callback(new Error('请输入合法的邮箱账号，如XXX@XXX.COM'))
    }
    // 验证手机号规则
    var checkMobile = (rules, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^(0|86|17951)?(13[0-9]|15[0123456789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regMobile.test(value)) {
        // 合法邮箱
        return callback()
      }
      // 不合法的邮箱
      callback(new Error('请输入正确的手机号'))
    }
    return {
      // 获取用户列表数据
      queryInfo: {
        query: '',
        // 当前页数
        pagenum: 1,
        pagesize: 2
      },
      usersList: [],
      total: 0,
      // 控制对话框的显示与隐藏
      addDialogVisible: false,
      // 所有角色数据列表
      rolesList: [],
      // 添加用户表单数据
      addForm: {
        username: '',
        mobile: '',
        email: '',
        password: ''
      },
      // 添加表单的验证规则对象
      addFormRules: {
        username: [{
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        },
        {
          min: 5,
          max: 12,
          message: '用户名长度必须在5~12个字符之间',
          trigger: 'blur'
        }
        ],
        password: [{
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        },
        {
          min: 6,
          max: 18,
          message: '密码长度必须在6~18个字符之间',
          trigger: 'blur'
        }
        ],
        mobile: [{
          validator: checkMobile,
          trigger: 'blur'
        }],
        email: [{
          validator: checkEmail,
          trigger: 'blur'
        }]
      },
      // 监听修改用户信息对话框的事件
      editDialogVisible: false,
      // 查询到的用户信息
      editForm: {},
      // 修改表单的验证规则对象
      editFormRules: {
        mobile: [{
          validator: checkMobile,
          trigger: 'blur'
        }],
        email: [{
          validator: checkEmail,
          trigger: 'blur'
        }]
      },
      // 分配角色对话框数据
      userInfo: {},
      // 展示分配角色的对话框
      setRoleDialogVisible: false,
      // 已选中的角色Id
      selectedRoleId: ''
    }
  },
  created () {
    this.getUsersList()
  },
  methods: {
    async getUsersList () {
      const {
        data: res
      } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$msg.error('获取用户列表失败')
      }
      this.usersList = res.data.users
      this.total = res.data.total
    },
    // 监听pageSize更改事件
    handleSizeChange (newSize) {
      this.queryInfo.pagesize = newSize
      this.getUsersList()
    },
    // 监听页码更改事件
    handleCurrentChange (newPage) {
      this.queryInfo.pagenum = newPage
      this.getUsersList()
    },
    // 监听switch开关状态的事件
    async userStateChanged (userinfo) {
      // console.log(userinfo.mg_state)
      const {
        data: res
      } = await this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$msg.error('更新用户状态失败')
      }
      this.$msg.success('更新用户状态成功')
    },
    // 监听添加用户对话框关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 监听修改用户对话框关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 添加用户
    addUser () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return ''
        // 发送请求
        const {
          data: res
        } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) {
          this.$msg.error('添加用户失败！')
        }
        this.$msg.success('添加成功！')
        // 隐藏对话框
        this.addDialogVisible = false
        // 重新获取用户列表数据
        this.getUsersList()
      })
    },
    // 弹出修改用户对话框
    async showEditDialog (id) {
      const {
        data: res
      } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$msg.error('修改用户信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 修改用户信息并提交
    editUserInfo () {
      this.$refs.editFormRef.validate(async valid => {
        // 不合法返回上一步
        if (!valid) return ''
        // 发起请求
        const {
          data: res
        } = await this.$http.put('users/' + this.editForm.id, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$msg.error('更新失败')
        }
        // 成功后=》1.关闭对话框
        this.editDialogVisible = false
        // 刷新列表
        this.getUsersList()
        // 提示修改成功
        this.$msg.success('更新用户信息成功')
      })
    },
    // 根据Id删除用户
    async removeUserById (id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // 如果确认删除则返回值为confirm字符串
      // 如果取消删除则返回值为cancel字符串
      if (confirmResult !== 'confirm') {
        return this.$msg.info('已取消操作')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      if (res.meta.status !== 200) {
        return this.$msg.error('删除用户失败！')
      }
      this.$msg.success('删除用户成功')
      this.getUsersList()
      // 重置页码
      this.queryInfo.pagenum = 1
    },
    // 打开分配角色对话框并获取数据
    async setRole (userInfo) {
      this.userInfo = userInfo
      // 打开对话框之前获取所有角色列表数据
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        this.$msg.error('获取角色列表失败！')
      }
      this.rolesList = res.data
      this.setRoleDialogVisible = true
    },
    // 提交用户修改的数据
    async saveRoleInfo () {
      if (!this.selectedRoleId) {
        return this.$msg.error('请选择要分配的角色')
      }
      const { data: res } = await this.$http.put(`users/${this.userInfo.id}/role`, { rid: this.selectedRoleId })
      if (res.meta.status !== 200) {
        this.$msg.error('分配角色失败')
      }
      this.$msg.success('分配角色成功')
      this.getUsersList()
      this.setRoleDialogVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
